//
//  SearchHistoryView.swift
//  TRHouse
//
//  Created by zhu xietong on 2018/5/11.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import UIKit
import Eelay

open class DeleteOptionV: FOptionV {
    
    required public init() {
        super.init()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open var canDeleteOne:Bool{
        get{
            return false
        }
    }
    
    open override func setOptionLayout() {
        
        self.edeg = UIEdgeInsets(top: 6, left: 14, bottom: 6, right: 14)
        titleL.text = "标签".loc
        titleL.font = UIFont.systemFont(ofSize: 16)
        let clickBt = UIButton()
        
        if canDeleteOne{
            self.eelay = [
                [titleL,[ee.L.Y,[8,0]]],
                [imgV,[ee.R.Y],26,"26"],
                [clickBt,[imgV,ee.L,ee.R],[ee.T.L.B]],
            ]
        }else{
            eelay = [
                [titleL,[ee.L.Y.R,[edeg.left,0,-edeg.right]]],
                [clickBt,[ee.T.L.B.R]],
            ]
        }
        
        self.setContentConstrainToHighLever()
        
        imgV.setImage(UIImage(named: "selectMark2"), for: .normal)
        
        _ = self.bsui.background(color: .color(light: "#ccc3", dark: "#ccc2")).set(radius: 14, width: nil, color: nil)
        
        _ = titleL.ui.font13.text(color: ._foreground).center
        imgV.addTarget(self, action: #selector(tag_touched), for: .touchUpInside)
        
        clickBt.addTarget(self, action: #selector(touchItem), for: .touchUpInside)
    }
    
    @objc open func touchItem() {
        self.deletate?.active(onwer: self, actionID: "search", data: mo.model)
    }
    
    override open func tag_touched()
    {
        self.deletate?.active(onwer: self, actionID: "delete", data: mo.model)

//        if let v = self.superview as? METagView{
//            self.pressedAction(self.tag,imgV.isSelected,self.mo.model, METagView())
//        }
    }
    
    open override var intrinsicContentSize: CGSize{
        var s_w = self.edeg.left + self.edeg.right + self.titleL.intrinsicContentSize.width
        if canDeleteOne{
            s_w = s_w + 30
        }
        
        let s_h = self.edeg.top + self.edeg.bottom + self.titleL.intrinsicContentSize.height
        return CGSize(width: s_w, height: s_h)
    }
    
    
    
    open override func mo_model_reload() {
        self.titleL.text = mo.model["content",""]
    }
    
}


open class SearchHistoryView: EeBottomToggleView,TableVConfig{
    
    public static var recommends = NSMutableArray(){
        didSet{
            __post(notify: SearchHistory.Notice.updateHot, object: SearchHistoryView.recommends, userInfo: nil)
        }
    }
    
    public var historyMananger:SearchHistory = SearchHistory.shared
    {
        didSet{
            tableView.load(sections: sections, selector: selector)
            tableView.separatorStyle = .none
            tableView.backgroundColor = ._background

        }
    }

    public func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        if actionID == "updateTable"
        {
            tableView.beginUpdates()
            tableView.endUpdates()
        }
        if actionID == "searchHistory"
        {
            self.searchAction(model["history",""])
            self.hidden()
            
        }
    }
    
    public weak var owner:UIViewController?{
        didSet{
            self.container = owner?.view
        }
    }

    public let tableView = UITableView(frame: .zero, style: .plain)
    
    public var searchAction:(String)->Void = {_ in}
    
    public var historySection:[[String:Any]]{
        get{
            let history = historyMananger.all()
            var sec = [[String:Any]]()
            if history.count > 0{
                sec.append(["id":"header","manager":historyMananger,"title":"搜索历史".loc])
                sec.append(["id":"history","manager":historyMananger])
            }
            return sec
        }
    }
    public var hotSection:[[String:Any]]{
        get{
            let history = SearchHistoryView.recommends
            var sec = [[String:Any]]()
            if history.count > 0{
                sec.append(["id":"header","title":"热搜话题".loc])
                sec.append(["id":"hot"])
            }
            return sec
        }
    }
    
    
    open var sections:TP.section {
        get{
            let sec:TP.section = [
                historySection,
                hotSection,
            ]
            return sec
        }
    }
    
    public var selector:TP.selector = [
        "id<history>":HistoryCell.self,
        "id<hot>":HotCell.self,
        "id<header>":HistoryHeaderCell.self,
    ]

    
  
    open override func addLayoutRules() {
        eelay = [
            [tableView,[ee.T.L.B.R]]
        ]
        tableView.mo_theme = mo_theme
        configTables(tables: tableView)
        tableView.hidenMoreLine()
        tableView.separatorStyle = .none
        tableView.backgroundColor = ._background
//        tableView.reloadData()
        __notice.observer(SearchHistory.Notice.updateHistory,SearchHistory.Notice.updateHot) {[weak self] (type, notify) in
            self?.reloadHistory()
        }
        
    }
    
    open func reloadHistory() {
//        tableView.model <-- ("section0",historySection.mutable_array,NodeInsert.dictValue)
        tableView.backgroundColor = ._background

        tableView.separatorStyle = .none
        tableView.load(sections: sections, selector: selector)
        tableView.separatorStyle = .none
        tableView.reloadData()
//        tableView.reloadSections(IndexSet(integer: 0), with: .fade)
    }
    
}

open class TagsField<OptionV:FOptionV>:FieldView,EeActionDelegate
{
    public var historyMananger:SearchHistory = SearchHistory.shared

    public func active(onwer: Any, actionID: String, data: NSMutableDictionary) {
        switch actionID {
        case "delete":
            historyMananger.delete(data["content",""])
        case "search":
//            SearchHistory.shared.add(history:data["content",""])
            tapHistoryAction(data["content",""])
        default:
            break
        }
    }
    
    open var options = NSMutableArray()
    public var tagsV = OptionTagsView()
    public var option_view_class:FOptionV.Type = OptionV.self
    
    public var deleteAction:(NSMutableDictionary) ->Void = {_ in}
    
    public var tapHistoryAction:(String) ->Void = {_ in}

    
    required public init() {
        super.init()
        self.option_view_class = OptionV.self
    }
    
    required public init(frame: CGRect) {
        fatalError("init(frame:) has not been implemented")
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override open func addLayoutRules() {
        self.option_view_class = OptionV.self
        
        self.eelay = [
            [tagsV,[ee.T.L.B.R]]
        ]
        
        tagsV.delegate = self
        
        self.loadOptionStyle()
        tagsV.add(tags: options)

    }
    
    
    override open func get_string_value() -> String {
        
        
        var tags = [String]()
        
        options.list { (dict:NSMutableDictionary, i) in
            let s = dict["title",""]
            tags.append(s)
        }
        
        
        if tags.count > 0
        {
            
            let va = tags.joined(separator: "#") + "#"
            return va
        }
        
        
        return mo.model[FK.emptyV,""]
        
    }
    
    
    
    open func delete(tag:NSMutableDictionary) {
        var obj:NSMutableDictionary?
        //        weak var wself = self
        options.listObj { (dict:NSMutableDictionary) in
//            print("===UUU|\(dict)")
        if dict["name","err1"] == tag["name","err2"]
        {
            obj = dict
        }
        }
        if let fobj = obj
        {
            options.remove(fobj)
        }
        self.deleteAction(mo.model)
    }
    
    
    open func loadOptionStyle() {
        tagsV.tagType = option_view_class
        tagsV.singleLine = false
        tagsV.padding = UIEdgeInsets.zero
        tagsV.insets = 6
        tagsV.lineSpace = 6
        
        weak var wself = self
        tagsV.selectedAction = {
            (index:Int,selected:Bool,obj:AnyObject,tview:METagView)
            in
            if let dict = obj as? NSMutableDictionary
            {
                wself?.delete(tag: dict)
            }
        }
    
    }
    
    
    
    open override func mo_model_reload() {
        if let manager = mo.model.object(forKey: "manager") as? SearchHistory
        {
            historyMananger = manager
        }
        self.options = DataNode.path(node: FK.options, mo.model, value: NSMutableArray())
        self.tagsV.remove()
        self.tagsV.add(tags: options)
        tagsV.updateConstraints()
        
    }
}



extension SearchHistoryView{
    
    
    
    open class HistoryHeaderCell:JoTableCell{
        open var historyMananger:SearchHistory = SearchHistory.shared
        let titleL = UILabel()
        let tashBt = UIButton()
        
        open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
            tashBt.ui.nimage(UIImage(named: "tag_tash")?.dynamicImage(color: .__foregroundWeak))
        }

        open override func addLayoutRules() {
            contentView.eelay = [
                [titleL,[ee.T.L.B,[16,AppTheme.edge,0]]],
                [tashBt,[ee.R,-AppTheme.edge],[titleL,ee.Y]],
//                [__line,[ee.L.B.R,[AppTheme.edge,0,-AppTheme.edge]],"\(TP.separatorHeight)"]
            ]
          
            tashBt.addTarget(self, action: #selector(clear), for: .touchUpInside)
        }
        open override func mo_model_reload() {
            __line.backgroundColor = mo_theme.separator
            titleL.ui.font17.text(color: ._foregroundWeak).text("搜索历史".loc)
            tashBt.ui.nimage(UIImage(named: "tag_tash")?.dynamicImage(color: .__foregroundWeak))
            contentView.backgroundColor = ._background

            super.mo_model_reload()
            if let manager = mo.model.object(forKey: "manager") as? SearchHistory
            {
                historyMananger = manager
            }
            titleL.text = mo.model["title",""]
        }
        
        @objc open func clear() {
            historyMananger.clearAll()
        }
    }
    
    open class HotCell:HistoryCell{
        open override func mo_model_reload() {
            let obj:[String : Any] = [
                FK.options:SearchHistoryView.recommends
            ]
            
            contentView.backgroundColor = ._background

            tagsV.mo.model = obj.mutable_dictionary
        }
    }
    
    open class HistoryCell: JoTableCell {
        public var tagsV = TagsField<DeleteOptionV>()
        public var historyMananger:SearchHistory = SearchHistory.shared

        open override func addLayoutRules() {
            contentView.eelay = [
                [tagsV,[ee.T.L.B.R,[14,AppTheme.edge,-14,-AppTheme.edge]]]
            ]
            tagsV.tagsV.preferredMaxLayoutWidth = Swidth - 2 * AppTheme.edge
            tagsV.tagsV.insets = 10
            tagsV.tagsV.lineSpace = 10
           
            weak var wself = self
            tagsV.deleteAction = {
                _ in
                wself?.tellUpdatesTable()
            }
            
            tagsV.tapHistoryAction = {
                str in
                wself?.active(ID: "searchHistory", object: ["history":str])
            }
            
            
        }
        open func tellUpdatesTable() {
            
            tagsV.mo_model_reload()
            self.delegate?.touch(cell: self, actionID: "updateTable", model: mo.model)
        }
        open override func mo_model_reload() {

            if let manager = mo.model.object(forKey: "manager") as? SearchHistory
            {
                historyMananger = manager
            }
            let obj:[String : Any] = [
                FK.options:historyMananger.all(limit: 10)
            ]
              
        
            tagsV.mo.model = obj.mutable_dictionary
         
            contentView.backgroundColor = ._background

        }
    }
    
    
    
}
